
import vuex from "vuex";

let fs = window.require("fs");
let download = window.require("download");

const { ipcRenderer } = window.require("electron");

const kuwoapi = vuex.createNamespacedHelpers("kuwoapi");
const wangyiyunapi = vuex.createNamespacedHelpers("wangyiyunapi");

// 判断调用哪个音乐源
function returnmapActions(source) {
  if (source === "kuwo") {
    return kuwoapi.mapActions(["getLyric", "getMusicUrl"]);
  } else if (source === "wangyiyun") {
    return wangyiyunapi.mapActions(["getLyric", "getMusicUrl"]);
  }
}

export default {

  async playMusic(e, self) {

    // 停止播放歌曲
    self.$store.commit('setState', { musicSrc: '' })

    if (!e) {
      return self.$message({
        type: 'warning',
        message: "试听列表中没歌曲啦！"
      })
    }

    let api = returnmapActions(e.source);

    let url;
    // 查看有无下载本地文件
    if (e.filename) {
      // 读取MP3的buffer
      let buf = fs.readFileSync(e.filename);
      if (buf) {
        // 把buffer数组转为Uint8Array数组
        buf = Uint8Array.from(buf);
        // 创建文件二进制流
        let blob = new Blob([buf]);
        // 根据二进制流创建播放url
        url = window.URL.createObjectURL(blob);
      }
    }

    // 查看有无播放地址缓存
    // if (!url && self.songUrls[e.rid]) {
    //   url = self.songUrls[e.rid];
    // }

    // 无缓存则发送请求获取歌曲播放地址
    if (!url) {
      try {
        let res = await api.getMusicUrl.call(self, e.rid);
        if (res.code === 200) {
          // 缓存播放地址
          // self.songUrls[e.rid] = res.url;
          url = res.url;
        }
      } catch (err) {
        // 酷我音乐api的bug，找不到音乐播放地址
        if (err === "Song:url_notfound") {
          self.$message({
            showClose: true,
            message: "网络出错啦",
            type: "error",
          });
        }
      }
    }

    console.log(url)

    // 播放歌曲
    self.$store.commit("setState", {
      musicSrc: url,
      isPlaying: true,
      currentTime: "0:00",
      totalTime: e.songTimeMinutes,
      artist: e.artist,
      name: e.name,
      imgsrc: e.imgsrc,
    });

    // 同时发起请求获取歌词，但不阻塞歌曲正常播放
    api.getLyric
      .call(self, e.rid)
      .then((lyric) => {
        if (lyric) self.$store.commit("setState", { lyric });
      })
      .catch((err) => {
        self.$message({
          type: 'error',
          message: "网络出错啦"
        })
      });
  },

  onadd(e, self) {
    let Muse_PlayList = ipcRenderer.sendSync('getStore', "Muse_PlayList") || []
    Muse_PlayList.push(e)
    ipcRenderer.send("setStore", "Muse_PlayList", Muse_PlayList);
    self.$message({
      type: 'success',
      message: "添加成功"
    })
  },

  downloadMusic(e, self) {

    let api = returnmapActions(e.source);

    // 告诉用户开始下载
    self.$message({
      message: "正在下载",
    });

    let url;

    // 查看有无播放地址缓存
    // if (self.songUrls[e.rid]) {
    //   url = self.songUrls[e.rid];
    // }

    // 无缓存则发送请求
    api.getMusicUrl.call(self, e.rid).then(async (res) => {
      if (res.code === 200) {
        // 缓存播放地址
        // self.songUrls[e.rid] = res.url;
        url = res.url;

        // download.js
        // 创建文件夹
        if (!fs.existsSync("D:\\museDownload"))
          fs.mkdirSync("D:\\museDownload");

        // 保存为的文件名
        let filename =
          "D:\\museDownload\\" + e.name + " - " + e.artist + ".mp3";

        // 下载到文件夹
        download(url).then((buf) => {
          // 写入文档
          fs.writeFile(filename, buf, (err) => {
            if (err) {
              // 下载失败
              self.$message({
                type: "success",
                message: "下载失败",
              });
              return;
            }
            // 下载成功告诉用户在哪里查看
            self.$message({
              type: "success",
              message: "下载成功，请查看" + filename,
            });

            // 下载记录保存到本地electron-store
            e.filename = filename;
            let Muse_Download =
              ipcRenderer.sendSync("getStore", "Muse_Download") || [];
            Muse_Download.push(e);
            ipcRenderer.send("setStore", "Muse_Download", Muse_Download);
          });
        });
      }
    }).catch(err => {
      self.$message({
        type: 'error',
        message: "网络出错啦"
      })
    });
  }
}